/*
 * JNIReferences.h  0.4.0 / Nov 14, 2010
 *
 * Copyright (c) 2010 - 2011, cute4j.com and contributors.
 *
 * This software is licensed under the LGPL version 2.1 license.
 * A copy of this license is included in the file LICENSE-LGPL.txt.
 */
#ifndef JNIREFERENCES_H
#define JNIREFERENCES_H

#include "JNIWrapper.h"

// GlobalReference Template. ---------------------------------------------------

/*!
 * \brief Global Reference.
 *
 * \author Slobodan Vrkacevic
 * \version 0.4.0
 */
template<typename T>
class GlobalReference
{
public:
  GlobalReference(JNIEnv *env, T t);
  virtual ~GlobalReference();
private:
  GlobalReference(const GlobalReference &);
public:
  inline T ref() const;
protected:
  JNIEnv *m_env;
  T m_obj;
};

// GlobalReference :: Public Constructor. --------------------------------------

/*!
 * \brief Constructs new GlobalReference object.
 *
 * \param env the JNIEnv pointer
 * \param t the reference type
 */
template<typename T>
GlobalReference<T>::GlobalReference(JNIEnv *env, T t)
{
  if (t) {
    m_obj = static_cast<T>(JNIWrapper::newGlobalRef(env, t));
    Q_ASSERT(env);
    m_env = env;
  } else {
    m_obj = 0;
  }
}

// GlobalReference :: Public Destructor. ---------------------------------------

/*!
 * \brief Destroys GlobalReference object.
 */
template<typename T>
GlobalReference<T>::~GlobalReference()
{
  if (m_obj) {
    m_env->DeleteGlobalRef(m_obj);
  }
}

// GlobalReference :: Private Constructor. -------------------------------------

template<typename T>
GlobalReference<T>::GlobalReference(const GlobalReference &)
{
  // copy constructor is disabled.
}

// GlobalReference :: Public Inline Member Function. ---------------------------

/*!
 * \brief Returns global reference.
 *
 * \return global reference
 */
template<typename T>
inline T GlobalReference<T>::ref() const
{
  return m_obj;
}

// GlobalReference :: Explicit Template Instantiations. ------------------------

template class GlobalReference<jobject>;
template class GlobalReference<jstring>;
template class GlobalReference<jclass>;
template class GlobalReference<jbyteArray>;

// GlobalReference :: Template Specializaions. ---------------------------------

typedef GlobalReference<jobject> GlobalJObject;
typedef GlobalReference<jstring> GlobalJString;
typedef GlobalReference<jclass> GlobalJClass;
typedef GlobalReference<jbyteArray> GlobalJByteArray;

#endif // JNIREFERENCES_H
